<?php
namespace app\common\tool;

use EasyWeChat\Factory;
use EasyWeChat\Payment\ProfitSharing\Receiver;
use EasyWeChat\Payment\ProfitSharing\Requests\ProfitSharingRequest;

class Wechat extends Base {
    public static function get_wechat() {
        $request = loader()->loadAny('request', 'Base');
        $loginType = $request->get_route();
        return config('wechat.' . $loginType);
    }

    public static function get_oxy_pay() {
        $request = loader()->loadAny('request', 'Base');
        $loginType = $request->get_route();
        $oxyPay = config('wechat.oxy_pay');
        if(!isset($oxyPay[$loginType])) {
            throw new \Exception('请求来源异常或商户号已解除绑定');
        }
        return $oxyPay[$loginType];
    }

	public static function miniprogram($loginType = null) {
        if($loginType) {
		    $config = config('wechat.' . $loginType);
		} else {
            $config = static::get_wechat();
        }
        return Factory::miniProgram($config);
	}

    public static function OfficialAccount($loginType = null) {
        if($loginType) {
            $config = config('wechat.' . $loginType);
        } else {
            $config = static::get_wechat();
        }
        return Factory::OfficialAccount($config);
    }

	public static function payment($loginType = null) {
        if($loginType) {
            $config = config('wechat.' . $loginType);
            $oxyPayConfig = config('wechat.oxy_pay');
            if(!isset($oxyPayConfig[$loginType])) {
                throw new \Exception('商户号已解除绑定');
            }
            $oxyPay = $oxyPayConfig[$loginType];
        } else {
            $config = static::get_wechat();
            $oxyPay = static::get_oxy_pay();
        }

		$config = array_merge($config, [
	        'app_id'             => $config['app_id'],
	        'mch_id'             => $oxyPay['wechat_service_merid'],
	        'key'                => $oxyPay['wechat_service_key'],
	        'cert_path'          => $oxyPay['wechat_service_client_cert'],
	        'key_path'           => $oxyPay['wechat_service_client_key'],
	        'notify_url'         => $oxyPay['notify_url']
	    ]);

	    $app = Factory::payment($config);

        return $app;
	}

    //获取access_token
    public static function get_access_token() {
        $config = static::get_wechat();
        $curl = loadTool('Curl');
        $atResult = $curl->post('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $config['app_id'] . '&secret=' . $config['secret'], []);
        $atResult = json_decode($atResult, true);
        return $atResult['access_token'];
    }

	public static function get_code($path, $scene)
    {
    	$access_token = static::get_access_token();

        $data = ['path' => $path, 'scene' => $scene];
        $headers = array();
        $headers[] = 'User-Agent: Apipost client Runtime/+https://www.apipost.cn/';
        $headers[] = 'Content-Type: application/json';
        $curl = loadTool('Curl');
        $result = $curl->set_headers($headers)->post('https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $access_token, $data, 'json_encode');
        $base64 = base64_encode($result);
        return $result;
    }

    public static function createorder($data) {
    	$access_token = static::get_access_token();
        $curl = loadTool('Curl');
        $result = $curl->post('https://api.weixin.qq.com/shop/pay/createorder?access_token=' . $access_token, $data, 'json_encode');
        return $result;
    }

    //发送订单已支付消息
    public function send_order_pay() {
        $accessToken = static::get_access_token();

        $data = [
            'number1' => ['value' => '32532653634634634436346'],
            'amount2' => ['value' => 5.00],
            'date3' => ['value' => "2025-05-22 14:30:00"],
            'thing4' => ['value' => '富硒大米'],
            'name6' => ['value' => '谢宗星']
        ];

        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
        $postData = [
            'touser' => 'oEEhh7NKh9wAY-XChFf6VUJqnLuA',
            'template_id' => 'J7xezhaQu2VEClcS5GUv1j5QeQWyR9kE-4t4GZoBRiM',
            'page' => '/pages-merchant/order-product/order-product',
            'data' => $data,
            'miniprogram_state' => 'trial'// 可选：formal（正式版）、trial（体验版）、developer（开发版）
        ];
        $result = loadTool('Curl')->body($url, $postData, 'json_encode');

        $resData = json_decode($result, true);
        
        if ($resData['errcode'] === 0) {
            return json(['code' => 200, 'msg' => '消息发送成功']);
        } else {
            \think\Log::error('订阅消息发送失败');
            \think\Log::error($resData);
            return json(['code' => 500, 'msg' => '消息发送失败: ' . $resData['errmsg']]);
        }
    }
}
